package com.example.dialog.Tools;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;

//该工具类重写了SQLiteOpenHelper类，用于保存历史搜索记录
public class DatabaseHelperForSearchHistory extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "searchHistory.db";
    private static final int DATABASE_VERSION = 1;

    public DatabaseHelperForSearchHistory(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_TABLE = "CREATE TABLE searchHistory ("
                + "id INTEGER PRIMARY KEY AUTOINCREMENT, "
                + "searchText TEXT)";
        db.execSQL(CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (oldVersion != newVersion) {
            db.execSQL("DROP TABLE IF EXISTS searchHistory");
            onCreate(db);
        }
    }

    public void saveSearchHistory(String searchText) {  // 保存记录
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("searchText", searchText);

        // 查询searchHistory表，检查是否已存在相同的searchText
        Cursor cursor = db.query("searchHistory", null, "searchText= ?", new String[]{searchText}, null, null, null);
        boolean exists = cursor.getCount() > 0;

        if (!exists) {
            // 如果不存在，执行插入操作
            db.insertOrThrow("searchHistory", null, values);
        }

        // 关闭Cursor和数据库连接
        cursor.close();
        db.close();
    }
    public void clearSearchHistory() {  //清除记录
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete("searchHistory", null, null);
        db.close();
    }

    public List<String> getAllSearchHistory() {
        List<String> historyList = new ArrayList<>();
        String selectQuery = "SELECT * FROM searchHistory";

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        if (cursor.moveToFirst()) {
            do {
                String history = cursor.getString(cursor.getColumnIndex("searchText"));
                historyList.add(history);
            } while (cursor.moveToNext());
        }
        cursor.close();
        db.close();
        return historyList;
    }
}